#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import base64
import os
import sys

def fix_image_files():
    image_dir = "/Users/wangqi/Documents/code/privateorder/pan/halo/application/src/main/resources/themes/alibaba-b2b-theme/assets/images"
    
    print("🔧 开始修复图片格式问题...")
    
    # 遍历所有图片文件
    for filename in os.listdir(image_dir):
        if filename.endswith(('.jpg', '.jpeg', '.png', '.gif', '.ico')):
            file_path = os.path.join(image_dir, filename)
            
            if os.path.isfile(file_path):
                print(f"📸 处理文件: {filename}")
                
                try:
                    # 读取文件内容
                    with open(file_path, 'r', encoding='utf-8') as f:
                        content = f.read().strip()
                    
                    # 解析JSON
                    data = json.loads(content)
                    base64_data = data['source']['data']
                    media_type = data['source']['media_type']
                    
                    # 移除Base64前缀（如果有的话）
                    if base64_data.startswith('data:'):
                        base64_data = base64_data.split(',', 1)[1]
                    
                    # 解码Base64数据
                    binary_data = base64.b64decode(base64_data)
                    
                    # 写入二进制文件
                    with open(file_path, 'wb') as f:
                        f.write(binary_data)
                    
                    print(f"  ✅ 成功修复: {filename} ({len(binary_data)} bytes)")
                    
                except Exception as e:
                    print(f"  ❌ 修复失败: {filename} - {str(e)}")
    
    print("\n🎉 图片修复完成！")
    
    # 显示修复后的文件信息
    print("\n📋 修复后的文件信息:")
    for filename in sorted(os.listdir(image_dir)):
        if filename.endswith(('.jpg', '.jpeg', '.png', '.gif', '.ico')):
            file_path = os.path.join(image_dir, filename)
            if os.path.isfile(file_path):
                file_size = os.path.getsize(file_path)
                print(f"  {filename}: {file_size} bytes")

if __name__ == "__main__":
    fix_image_files()